package com.scalar.chiptrack.sales.actions.quote;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.SplitQuotationForm;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SplitLineItemsComparator;
import com.scalar.chiptrack.sales.actions.SalesOrderAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

/**
 * User: Sujan
 * Date: Mar 13, 2007
 * Time: 12:23:29 PM
 */
public class SplitQuotationAction extends ChipTrackAction
{
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        SplitQuotationForm splitQuotationForm = (SplitQuotationForm) form;
        //Get the session, to retrieve the values
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, request.getServletPath() + "?" + request.getQueryString() );
            return ( mapping.findForward ( "login" ) );
        }
        HashMap info = (HashMap)request.getAttribute( SessionKeys.INFO_MESSAGES );
        HashMap errors = (HashMap)request.getAttribute( SessionKeys.ERROR_MESSAGES );
        if ( info == null )
        {
            info = new HashMap();
        }
        if ( errors == null )
        {
            errors = new HashMap();
        }
        String action = request.getParameter("action");
        if ( action == null || action.trim().length() == 0 )
        {
            action = "splitLineItems";
        }

        if( "splitLineItems".equalsIgnoreCase( action ) )
        {
            int quotationId = 0;
            try
            {
                quotationId = Integer.parseInt( request.getParameter( "quotationId" ) );
            }
            catch ( NumberFormatException e ) {}

            ArrayList lineItems = QuotationDAO.loadOrderLineItemsWithCustomerPartNo ( quotationId, 0 );
            splitQuotationForm.setLineItems( lineItems );
            splitQuotationForm.setQuotationId( quotationId );
            if ( lineItems != null && lineItems.size() > 0 )
            {
                LineItem lineItem = (LineItem) lineItems.get( 0 );
                splitQuotationForm.setQuotationNo( lineItem.getSalesOrderNo() );
                for ( int i = (lineItems.size()-1); i >= 0 ; i-- )
                {
                    lineItem = (LineItem) lineItems.get( i );
                    if ( lineItem.getQuantity() > 0 )
                    {
                        lineItem.setSplitFromLineItemId( lineItem.getLineItemId() );
                        lineItem.setQtyAfterSplit( lineItem.getQuantity() );
                    }
                    else
                    {
                        lineItems.remove(i);
                    }
                }
            }
            return mapping.findForward( "splitQuotation" );
        }
        else if ( "submitSplitLineItems".equalsIgnoreCase( action ) )
        {
            ArrayList lineItems = splitQuotationForm.getLineItems();
            removeEmptyLineItems( lineItems );
            Collections.sort( lineItems, new SplitLineItemsComparator() );
            request.setAttribute( "isConfirm", "true" );
            return mapping.findForward( "splitQuotation" );
        }
        else if ( "editSplitLineItems".equalsIgnoreCase( action ) )
        {
            request.setAttribute( "isConfirm", "false" );
            return mapping.findForward( "splitQuotation" );
        }
        else if ( "confirmSplitLineItems".equalsIgnoreCase( action ) )
        {
            ArrayList lineItems = splitQuotationForm.getLineItems();
            DBTransaction dbTransaction = null;
            boolean success = false;
            try
            {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                QuotationDAO.splitQuotationLineItems( dbTransaction, lineItems, user.getUserId() );
                dbTransaction.commit();
                success = true;
                info.put ( "Line Items have been split and saved successfully", null );
            }
            catch( ScalarException e )
            {
                errors.put ( "Could not Split Line Items", null );
                e.printStackTrace();
            }
            finally
            {
                if ( dbTransaction != null && !success )
                {
                    try { dbTransaction.rollback(); } catch ( DBXException e ) {}
                }
            }
            lineItems = QuotationDAO.loadOrderLineItemsWithCustomerPartNo ( splitQuotationForm.getQuotationId(), 0 );
            session.setAttribute ( "lineItems", lineItems );
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );
            session.setAttribute ( "maxLineItemNo", Integer.toString ( QuotationDAO.loadMaxLineItemNo ( splitQuotationForm.getQuotationId() ) ) );

            if ( splitQuotationForm.getIsReqFromTransferQuote() )
            {
                return new ActionForward ( "/transferQuotation.do?action=EditSalesOrder&customerId="+splitQuotationForm.getCustomerId() );
            }
            else //FROM MODIFY
            {
                return new ActionForward ( "/changeQuotation.do?action=EditQuotation&customerId="+splitQuotationForm.getCustomerId() );
            }
        }

        return null;
    }
    private void removeEmptyLineItems ( ArrayList lineItems )
    {
        int size = ( lineItems == null ) ? 0 : lineItems.size();
        for ( int i=(size-1); i >= 0; i-- )
        {
            LineItem lineItem = ( LineItem ) lineItems.get(i);
            if ( lineItem.getSplitFromLineItemId() <= 0 && lineItem.getLineItemId() <= 0 )
            {
                lineItems.remove(i);
            }
        }
    }
}
